package com.yanxinim.cn.ui.me.redpacket;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.callback.ListCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ArrayResult;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import com.xuan.xuanhttplibrary.okhttp.result.Result;
import com.yanxinim.cn.R;
import com.yanxinim.cn.adapter.BankCardAdapter;
import com.yanxinim.cn.adapter.BankCardSelectAdapter;
import com.yanxinim.cn.adapter.BankNameAdapter;
import com.yanxinim.cn.bean.WXUploadResult;
import com.yanxinim.cn.bean.event.EventNotifyByTag;
import com.yanxinim.cn.bean.redpacket.BankCardBean;
import com.yanxinim.cn.helper.DialogHelper;
import com.yanxinim.cn.helper.PaySecureHelper;
import com.yanxinim.cn.ui.base.BaseActivity;
import com.yanxinim.cn.ui.base.CoreManager;
import com.yanxinim.cn.ui.me.redpacket.alipay.AlipayHelper;
import com.yanxinim.cn.util.ToastUtil;
import com.yanxinim.cn.util.input.DecimalDigitsInputFilter;
import com.yanxinim.cn.util.secure.Money;

import org.w3c.dom.Text;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

/**
 * @ClassName BankWithdrawActivity
 * @Description 银行卡提现页面
 * @Author ChenXL
 * @Date 2021/5/28 14:44
 * @Version 1.0
 */
public class BankWithdrawActivity extends BaseActivity {

    public static String amount;// 提现金额 单位:元

    //银行logo
    ImageView ivBankLogo;
    //银行名称
    TextView tvBankName;
    //选择银行卡
    TextView tvSelectBankCard;
    //银行卡号
    TextView tvBankCardNo;
    //提现金额
    EditText etAccount;
    //零钱余额
    TextView tvBalance;
    //提现按钮
    Button btnWithdraw;

    List<BankCardBean> beanList = new ArrayList<>();

    //记录上一个选中，省的每次都进行for循环消耗内存
    int lastSelectBankCard = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bank_withdraw);
        initActionBar();
        initView();
        initData();
        getMyBankCard();
    }

    private void initActionBar() {
        getSupportActionBar().hide();

        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView mTvTitle = (TextView) findViewById(R.id.tv_title_center);
        mTvTitle.setText("零钱提现");
    }

    private void initView(){
        ivBankLogo = findViewById(R.id.ivBankLogo);
        tvBankName = findViewById(R.id.tvBankName);
        tvSelectBankCard = findViewById(R.id.tvSelectBankCard);
        tvBankCardNo = findViewById(R.id.tvCardNo);
        etAccount = findViewById(R.id.etAmount);
        tvBalance = findViewById(R.id.tvBalance);
        btnWithdraw = findViewById(R.id.btnWithdraw);

        etAccount.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(2), new InputFilter.LengthFilter(11)});

        tvSelectBankCard.setOnClickListener(view -> {
            showSelectBankCardAlart();
        });

        btnWithdraw.setOnClickListener(view -> {
            submitWithdraw();
        });
    }

    /**
     * 绑定部分数据：余额
     */
    private void initData(){
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        tvBalance.setText("零钱余额" + decimalFormat.format(coreManager.getSelf().getBalance()) + "元");
    }

    /**
     * 获取我的绑定银行卡列表
     */
    private void getMyBankCard(){
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);

        HttpUtils.get().url(coreManager.getConfig().MY_BANK_LIST)
                .params(params)
                .build()
                .execute(new ListCallback<BankCardBean>(BankCardBean.class) {

                    @Override
                    public void onResponse(ArrayResult<BankCardBean> result) {
                        if (result.getResultCode() == 1 && result.getData() != null) {
                            beanList = result.getData();
                            if (beanList.size() != 0) {
                                //取列表第一个数据做默认数据
                                beanList.get(0).setSelect(true);
                                if (tvBankName != null){
                                    tvBankName.setText(beanList.get(0).getBankName());
                                }
                                if (ivBankLogo != null){
                                    ivBankLogo.setImageResource(BankCardAdapter.getBankLogo(beanList.get(0).getBankCode()));
                                }
                                if (tvBankCardNo != null){
                                    String cardNo = beanList.get(0).getBankCardNo();
                                    String cardNoStr = "····  ····  ····  " + cardNo.substring(cardNo.length() - 4, cardNo.length());
                                    tvBankCardNo.setText(cardNoStr);
                                }
                            }
                        } else {
                            ToastUtil.showErrorData(BankWithdrawActivity.this);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtil.showNetError(BankWithdrawActivity.this);
                    }
                });
    }

    /**
     * 显示选择银行卡列表弹框
     */
    private void showSelectBankCardAlart(){

        Dialog bottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_bank_card_select, null);

        ListView listView = contentView.findViewById(R.id.mlvBankCard);
        BankCardSelectAdapter adapter = new BankCardSelectAdapter(mContext);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                beanList.get(lastSelectBankCard).setSelect(false);
                lastSelectBankCard = position;
                beanList.get(position).setSelect(true);
                adapter.notifyDataSetChanged();
            }
        });

        Button btnSure = contentView.findViewById(R.id.btnSure);
        btnSure.setOnClickListener(view -> {
            if (beanList == null || beanList.size() == 0){
                ToastUtil.showToast(BankWithdrawActivity.this, "当前没有银行卡，请先绑定银行卡");
                return;
            }
            if (lastSelectBankCard >= beanList.size()){
                ToastUtil.showToast(BankWithdrawActivity.this, "当前选择银行卡异常，请重新选择");
                return;
            }
            ivBankLogo.setImageResource(BankCardAdapter.getBankLogo(beanList.get(lastSelectBankCard).getBankCode()));
            tvBankName.setText(beanList.get(lastSelectBankCard).getBankName());

            String cardNo = beanList.get(lastSelectBankCard).getBankCardNo();
            String cardNoStr = "····  ····  ····  " + cardNo.substring(cardNo.length() - 4, cardNo.length());
            tvBankCardNo.setText(cardNoStr);
            bottomDialog.dismiss();
        });

        listView.setAdapter(adapter);
        adapter.setDatas(beanList);
        adapter.notifyDataSetChanged();

        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        layoutParams.height = getResources().getDisplayMetrics().heightPixels / 2;
        contentView.setLayoutParams(layoutParams);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
    }

    /**
     * 提交提现
     */
    private void submitWithdraw(){
        String moneyStr = etAccount.getText().toString().trim();
        if (beanList == null || beanList.size() == 0){
            ToastUtil.showToast(BankWithdrawActivity.this, "请先选择银行卡");
            return;
        }

        if (checkMoney(moneyStr)) {
            amount = Money.fromYuan(moneyStr);
            PaySecureHelper.inputPayPassword(this, this.getString(R.string.withdraw), amount, password -> {
//                AlipayHelper.auth(this, coreManager, password, userId -> {
                    withdraw(this, coreManager, beanList.get(lastSelectBankCard).getId(), amount, password);
//                });
            });
        }
    }

    /**
     * 通知后台提现，
     */
    public void withdraw(Activity activity, CoreManager coreManager, String bankAccountId, String money, String password) {
        DialogHelper.showDefaulteMessageProgressDialog(activity);

        final Map<String, String> params = new HashMap<>();
        params.put("amount", money);
        params.put("bankAccountId", bankAccountId);

        PaySecureHelper.generateParam(
                activity, password, params,
                "" + money + bankAccountId,
                t -> {
                    DialogHelper.dismissProgressDialog();
                    ToastUtil.showToast(activity, activity.getString(R.string.tip_pay_secure_place_holder, t.getMessage()));
                }, (p, code) -> {
                    HttpUtils.post().url(coreManager.getConfig().BANK_CARD_WITHDRAW)
                            .params(p)
                            .build()
                            .execute(new BaseCallback<WXUploadResult>(WXUploadResult.class) {

                                @Override
                                public void onResponse(ObjectResult<WXUploadResult> result) {
                                    DialogHelper.dismissProgressDialog();
                                    if (Result.checkSuccess(activity, result)) {
                                        EventBus.getDefault().post(new EventNotifyByTag(EventNotifyByTag.Withdraw));
                                        ToastUtil.showToast(activity, R.string.tip_withdraw_success);
                                        activity.finish();
                                    }
                                }

                                @Override
                                public void onError(Call call, Exception e) {
                                    DialogHelper.dismissProgressDialog();
                                    ToastUtil.showErrorData(activity);
                                }
                            });
                });
    }

    private boolean checkMoney(String moneyStr) {
        if (TextUtils.isEmpty(moneyStr)) {
            DialogHelper.tip(BankWithdrawActivity.this, getString(R.string.tip_withdraw_empty));
        } else {
            if (Double.valueOf(moneyStr) < 0.01) {
                DialogHelper.tip(BankWithdrawActivity.this, getString(R.string.tip_withdraw_too_little));
            } else if (Double.valueOf(moneyStr) > coreManager.getSelf().getBalance()) {
                DialogHelper.tip(BankWithdrawActivity.this, getString(R.string.tip_balance_not_enough));
            } else {// 获取用户code
                return true;
            }
        }
        return false;
    }
}
